import {ajax, init, loadComponent, getToken, util} from 'framework'
import {createRouter, createWebHashHistory} from "vue-router"
import Page404 from '../404.vue'
import {useStore, setRouter, loadUserInfo, getUser} from 'store'
import {createPinia} from 'pinia'
import {message, confirm} from 'heyui'
import axios from 'axios'
import {getLanguage,$t} from "./i18n.js";

let load = loadComponent
const loginPage=window._configs['PlatformConfig.LoginPage']||'login.vue'
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/login',
            name: 'Login',
            component: () => load(loginPage)
        },
        {
            path: '/404',
            name: '404',
            component: Page404
        },
        {
            path: '/',
            name: 'Index',
            component: () => load('layout.vue'),
            children: []
        },
        {
            path: '/:w+',
            redirect: '/login',
            name: 'notFound',
            hidden: true
        }
    ]
})
setRouter(router)

document.body.setAttribute('class', localStorage.theme || 'blue')
const whiteList = ['Login', '404', '403']
router.beforeEach((to, from, next) => {
    // console.log('route to',to)
    let name = to.name
    if (whiteList.indexOf(name) > -1) {
        if (name == 'Login') {
            let username = getUser().value.username
            if (username) {
                next('/')
            } else {
                next()
            }
        } else if (name == 'Index') {
            next({name: 'Home'})
        } else {
            next()
        }
    } else {
        let username = getUser().value.username
        if (!username) {
            next('/login')
        } else if (name == 'Index') {
            next({name: 'Home'})
        } else {
            next()
        }
    }
})
axios.interceptors.request.use(function (cfg) {
    let language=getLanguage()
    if (language){
        cfg.headers['Accept-Language']=language
    }

    // let token = sessionStorage['_token'];
    let realToken = getToken();
    if(realToken==null){
        return cfg;
    }
    // if(token!=realToken&&token!=null){
    //     cfg.headers['pre_token'] = token
    // }
    cfg.headers['token'] = realToken
    return cfg;
})
let showErrHandler

//同时(10纳秒内)发生多个错误时，提示最后一个
function showError(msg) {
    clearTimeout(showErrHandler)
    showErrHandler = setTimeout(() => {
        message({type: 'error', text: msg})
    }, 10);
}

let showLoginFlag = false
const showLogin = util.debounce(() => {
    if (showLoginFlag) {
        return
    }
    showLoginFlag = true
    confirm({
        content: '未登录或登录已过期，是否去登录?',
        onConfirm: () => {
            sessionStorage.clear()
            localStorage.removeItem('rmb_tk')
            getUser().value = {}
            location.hash = "/login"
            showLoginFlag = false
        },
        onCancel: () => {
            showLoginFlag = false
        }
    })
}, 300)
axios.interceptors.response.use(function (res) {

    let headers = res.headers
    let token = headers['token'];
    if (token) {
        sessionStorage.setItem("_token", token);
    } else if (headers['rtk']) {
        sessionStorage.removeItem("_token")
    }

    let isJson = res.headers['content-type'].indexOf('json') > -1;
    if (isJson && res.data) {
        if (res.data.success) {
            return res.data
        }
        let msg = res.data.description || res.data.message;
        if("success"==msg){
            return res.data
        }
        if (msg) {
            showError(msg)
        }
        return Promise.reject(res.data)
    } else {
        if (res.data && res.data.success == false) {
            return Promise.reject(res.data)
        }
        return isJson ? res.data : res;
    }
}, function (error) {
    // 对响应错误做点什么;没有权限401，去登录界面
    if (error.response?.data?.message){
        let data = error.response.data
        showError(data.message)
    }else if (!error.response) {
        showError("网络错误！")
    } else if (error.response.status === 401) {
        showLogin()
    } else if (error.response.status === 403) {
        showError("没有权限！")
    } else if (error.response.status === 500) {
        showError("服务器错误！")
    } else if (error.response.status === 404) {
        // window.$toast('网络错误')
        showError("页面未找到！")
    } else if (error.response.data) {
        let data = error.response.data
        showError(data.description || data.data || data.message)
    }
    return Promise.reject(error);
});
loadUserInfo()
    .catch(console.log).finally(e => {
        let app = init({})
        app.use(createPinia())
        app.use(router)

       // app.config.globalProperties.$i18n={locale :'en'};
     //   app.config.globalProperties.$t=t
        app.mount('#app')
    })

if(getToken()==null){
    localStorage.removeItem("user.token")
}
addEventListener("logout",evt =>{
    localStorage.removeItem("user.token")
})

